package com.example.jwtsso;

import io.jsonwebtoken.*;
import org.springframework.http.HttpHeaders;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtSsoSdk {
    private final String secretKey;
    private final String issuer;
    private final String audience;

    public JwtSsoSdk(String secretKey, String issuer, String audience) {
        this.secretKey = secretKey;
        this.issuer = issuer;
        this.audience = audience;
    }

    public String generateToken(Long userId, Integer roleId, String name) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + 3600000);

        return Jwts.builder()
                .setIssuer(issuer)
                .setAudience(audience)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .claim("user_id", userId)
                .claim("role_id", roleId)
                .claim("name", name)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public Map<String, Object> validateToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();

            if (!claims.getIssuer().equals(issuer) || !claims.getAudience().equals(audience)) {
                return null;
            }

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("user_id", claims.get("user_id"));
            userInfo.put("role_id", claims.get("role_id"));
            userInfo.put("name", claims.get("name"));
            return userInfo;
        } catch (JwtException e) {
            return null;
        }
    }

    public String getTokenFromHeader(HttpHeaders headers) {
        String authHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
}